<?php
/**
* 消息数据模型
* @date: 2018年6月5日 上午10:12:44
* @author: xiaocui
*/

namespace app\admin666\model;

use think\Model;

class Fields extends Model
{
    protected $autoWriteTimestamp = true;
    protected $updateTime = false;
    
    /**
    * 类型
    * @date: 2018年8月14日 下午3:07:44
    * @author: xiaocui
    * @param: variable
    * @return:
    */
    public function field_type(){
        $typearr = [
            ['name'=>'number','title'=>'数值','attr'=>'int'],
            ['name'=>'text','title'=>'单行文本','attr'=>'varchar'],
            ['name'=>'textarea','title'=>'多行文本','attr'=>'text'],
            ['name'=>'radio','title'=>'单选项','attr'=>'int'],
            ['name'=>'checkbox','title'=>'多选项','attr'=>'varchar'],
            ['name'=>'select','title'=>'下拉选项','attr'=>'int'],
            ['name'=>'datatime','title'=>'日期时间','attr'=>'int'],
            ['name'=>'ueditor','title'=>'百度编辑器','attr'=>'longtext'],
            ['name'=>'pic','title'=>'上传图片','attr'=>'varchar'],
        ];
        return $typearr;
    }
    
    /**
    * 编辑字段
    * @date: 2018年8月14日 上午11:44:11
    * @author: xiaocui
    * @param: variable
    * @return:
    */
    public function alter_table($data,$type=1){
        $minfo = model('models')->find($data['mid']);
        $table = config('database.prefix').$minfo['name'];
        $typearr = $this->field_type();
        $attr = '';
        foreach ($typearr as $val){
            if($data['type'] == $val['name']){
                $attr = $val['attr'];
            }
        }
        $attr = empty($attr)?'varchar(255)':$attr;
        if(in_array($attr, array('int','varchar'))){
            $len = intval($data['length']) > 0?$data['length']:255;
            $attr = "{$attr}({$len})";
        }
        
        if(trim($data['value']) == ''){
            $value = 'NULL';
        }elseif(is_numeric($data['value'])){
            $value = intval($data['value']);
        }else{
            $value = "'{$data['value']}'";
        }
        
        if($type==1){
            $sql = "ALTER TABLE `{$table}` ADD `{$data['name']}` {$attr} DEFAULT {$value} COMMENT '{$data['title']}'";
        }elseif($type==2){
            $sql = "ALTER TABLE `{$table}` MODIFY `{$data['name']}` {$attr} DEFAULT {$value} COMMENT '{$data['title']}'";
        }elseif($type==3){
            $sql = "ALTER TABLE `{$table}` DROP `{$data['name']}`";
        }
        $this->query($sql);
    }
}